from selenium import webdriver
import os
from setting import SAVE_PATH, FILE_NAME

a1="葬送的芙莉莲：第13话 同类厌恶"

def dan_mu_xml2ass(
    bilibili2ass_url="file:///"
    + os.getcwd()
    + "/bilibili%20ASS%20%E5%BC%B9%E5%B9%95%E8%BD%AC%E6%8D%A2%E7%BD%91%E7%AB%99/bilibili_ass.html",
    dan_mu_xml_path=SAVE_PATH + FILE_NAME + "/",
    dan_mu_xml_name=FILE_NAME + ".xml",
):
    '''
    把xml格式弹幕文件转换为ass
    '''
    # 读取弹幕js文件
    f_dan_mu_xml = open(dan_mu_xml_path + dan_mu_xml_name, "r", encoding="utf8")
    dan_mu_xml_str = f_dan_mu_xml.read()
    f_dan_mu_xml.close()

    op = webdriver.EdgeOptions()
    op.add_argument("-headless")
    # browser = webdriver.Edge(options=op)
    browser = webdriver.Edge()
    browser.get(url=bilibili2ass_url)
    browser.find_element_by_xpath(r"//input[@id='upload']")
    try:
        # ass_str=browser.execute_script(xml2ass_js_str,dan_mu_xml_name,dan_mu_xml_str)
        call_generateASS = """
        var danmaku = parseFile(arguments[1]);
        var ass ='\ufeff' + generateASS(setPosition(danmaku), {
        'title': document.title,
        'ori': arguments[0],
        });
        return ass;
        """
        ass_str = browser.execute_script(
            call_generateASS, dan_mu_xml_name, dan_mu_xml_str
        )
        browser.close()
    except e:
        browser.close()

    dan_mu_ass_name = os.path.splitext(dan_mu_xml_name)[0] + ".ass"
    with open(dan_mu_xml_path + dan_mu_ass_name, "w", encoding="utf8") as f:
        f.write(ass_str)

if __name__=="__main__":
    dan_mu_xml2ass()